<?php
/**
 * 写入丢失的推广消息
 */
class SaveTuigui extends ScriptBase
{	
	// 本地 http://t.test.com/esmj_script/script.php?request=SaveTuigui
	public function logic()
	{
		set_time_limit(0);
		$mysql = $this->mysql('tuiguang');
		$table = 'spread_uid_shared';   // 多数据的表
		$table2 = 'd_user_promo_codes'; // 需要插入的表
		$table3 = 'spread';             // 获取用户的推广码
        $data = $data2 = $data3 = [];

        $sql = "select uid from $table"; 
        $row = $mysql->query($sql);
        while ($row = $mysql->fetch_assoc()) {
        	$data[] = $row['uid'];
        }
        echo '<pre>';
        $sql2 = "select uid from $table2";
    	$row2 = $mysql->query($sql2);
    	while ($row2 = $mysql->fetch_assoc()) {
        	$data2[] = $row2['uid'];
        }
       
        // 取差集
        $result = array_diff($data,$data2);
        echo "$table2 缺少 $table 的数据".count($result);
        echo '<br>';
        $result2 = array_diff($data2,$data);
        echo "$table 缺少 $table2 的数据".count($result2);
        echo '<br>';
		foreach ($result as $v) {
			$sql5 = "select uid,share_code,created_at from $table3 where uid=$v";
			$row5 = $mysql->query($sql5);
			$data5 = [];
			while ($row5 = $mysql->fetch_assoc()) {
	        	$data5 = $row5;
	        }
			$sql3 = "select uid,share_code,addtime from $table where uid=$v ";
			$row3 = $mysql->query($sql3);
			while ($row3 = $mysql->fetch_assoc()) {
				if($data5){
					$row3['agent_code'] = $data5['share_code'];
					$row3['promo_built'] = strtotime($data5['created_at']);
				}else if($row3){
					$row3['agent_code'] = 0;
					$row3['promo_built'] = 0;
				}
	        	$data3[] = $row3;
	        }
		}
		$sql4 = "insert $table2 (uid,promo_code,promo_bound,agent_code,promo_built) value ";
		file_put_contents('log.txt',$sql4."\r\n",FILE_APPEND);
		$j=0;
		foreach ($data3 as $v) {
			$sql4 = "({$v['uid']},{$v['share_code']},{$v['addtime']},{$v['agent_code']},{$v['promo_built']}),";
			file_put_contents('log.txt',$sql4."\r\n",FILE_APPEND);
			$j++;
		}
		echo '<br>';
		echo "添加 $j 条数据成功"; // 209054
	}
}

/*
去重sql

DELETE a 
FROM spread_uid_shared a JOIN(
select max(id) id,uid from spread_uid_shared group by uid having count(*)>1
) b ON a.uid = b.uid
WHERE a.id < b.id

*/